package com.zzyl.serve.service.impl;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.TimeUnit;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.serve.domain.AlertData;
import com.zzyl.serve.domain.DeviceData;
import com.zzyl.serve.service.IAlertDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.serve.mapper.AlertRuleMapper;
import com.zzyl.serve.domain.AlertRule;
import com.zzyl.serve.service.IAlertRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.util.CollectionUtils;

/**
 * 报警规则Service业务层处理
 * 
 * @author MWJ
 * @date 2025-08-26
 */
@Service
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper, AlertRule> implements IAlertRuleService
{
    @Autowired
    private AlertRuleMapper alertRuleMapper;
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    @Autowired
    private IAlertDataService alertDataService;

    /**
     * 查询报警规则
     * 
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id)
    {
        return alertRuleMapper.selectById(id);
    }

    /**
     * 查询报警规则列表
     * 
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule)
    {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     * 
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule)
    {
        return alertRuleMapper.insert(alertRule);
    }

    /**
     * 修改报警规则
     * 
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule)
    {
        return alertRuleMapper.updateById(alertRule);
    }

    /**
     * 批量删除报警规则
     * 
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids)
    {
        return alertRuleMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除报警规则信息
     * 
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id)
    {
        return alertRuleMapper.deleteById(id);
    }

    @Override
    public void handleAlertJob() {
        //已启用的规则数不为空
        LambdaQueryWrapper<AlertRule> wrapper = Wrappers.<AlertRule>lambdaQuery().eq(AlertRule::getStatus, 1);
        long count = count(wrapper);
        if(count == 0){
            return;
        }
        //从redis中获取设备上报数据,不能为空
        List<Object> objectList = redisTemplate.opsForHash().values(CacheConstants.IOT_ALL_DEVICES_DATA_NEWEST);
        if(CollectionUtils.isEmpty(objectList)){
            return;
        }
        //转为deviceData格式，并对每条数据进行报警规则判断
        objectList.forEach(o->{
            List<DeviceData> deviceDataList = JSONUtil.toList(o.toString(), DeviceData.class);
            for (DeviceData deviceData : deviceDataList) {
                alertFilter(deviceData);
            }
        });
    }

    private void alertFilter(DeviceData deviceData) {
        //是否有对应的报警规则在运行
        LambdaQueryWrapper<AlertRule> wrapper = Wrappers.<AlertRule>lambdaQuery().eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getStatus,1)
                .in(AlertRule::getIotId, -1, deviceData.getIotId());
        List<AlertRule> alertRuleList = list(wrapper);
        if(CollectionUtils.isEmpty(alertRuleList)){
            return;
        }
        //设备上报时间是否在对应报警规则的监测时间范围内
        alertRuleList.forEach(ar->timeScopeOk(ar,deviceData));
    }

    private void timeScopeOk(AlertRule alertRule, DeviceData deviceData) {
        //设备上报时间距离现在时间是否已超过一分钟
        LocalDateTime alarmTime = deviceData.getAlarmTime();
        long time = LocalDateTimeUtil.between(alarmTime, LocalDateTime.now(), ChronoUnit.SECONDS);
        if(time > 60){
            return;
        }
        String[] split = alertRule.getAlertEffectivePeriod().split("~");
        LocalTime start = LocalTime.parse(split[0]);
        LocalTime end = LocalTime.parse(split[1]);
        LocalTime alarmTime1 = LocalTime.from(deviceData.getAlarmTime());
        if(alarmTime1.isBefore(start) || alarmTime1.isAfter(end)){
            return;
        }
        handleAlert(alertRule,deviceData);
    }

    private void handleAlert(AlertRule alertRule, DeviceData deviceData) {
        //之前用iotId作为小key 忽略了一个设备一条数据有多个functionId，导致value一直为1
        String field = deviceData.getFunctionId()+"_"+alertRule.getAlertRuleName()+"_"+deviceData.getIotId();
        String silentKey = field+"_"+CacheConstants.ALERT_RULE_SILENT_COUNT;
        //数据是否满足报警规则
        Long value = alertRule.getValue();
        String operator = alertRule.getOperator();
        Double dataValue = Double.parseDouble(deviceData.getDataValue());
        if(("<".equals(operator) && dataValue >= value) || (">=".equals(operator) && dataValue < value)){
            //不满足报警规则，删除redis中保存持续周期的key
            redisTemplate.opsForHash().delete(CacheConstants.ALERT_RULE_DURATION_COUNT,field);
            return;
        }
        redisTemplate.opsForHash().putIfAbsent(CacheConstants.ALERT_RULE_DURATION_COUNT,field,0);
        redisTemplate.opsForHash().increment(CacheConstants.ALERT_RULE_DURATION_COUNT,field,1);
        //是否达到了持续周期
        Integer dCount = (Integer) redisTemplate.opsForHash().get(CacheConstants.ALERT_RULE_DURATION_COUNT,field);
        //是否在沉默周期内
        Boolean silent = redisTemplate.hasKey(silentKey);
        if(dCount < alertRule.getDuration() || silent){
            return;
        }
        redisTemplate.opsForHash().delete(CacheConstants.ALERT_RULE_DURATION_COUNT,field);
        //设置沉默周期key到redis中,因为定时任务是每分钟获取一次，所以设置周期单位为分钟，让它到时间自动过期
        redisTemplate.opsForValue().set(silentKey,true,alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);
        //获取责任人，超级管理员，护理人员/维修人员
        Set<Long> ids = new HashSet<>();
        //超级管理员
        List<Long> adminIds = alertRuleMapper.getIdByRoleName("超级管理员");
        ids.addAll(adminIds);
        //为设备数据异常，找维修人员.固定在房间的在设置报警规则时，也就设置为设备异常数据。
        if(alertRule.getAlertDataType() == 1){
            List<Long> fUserIds = alertRuleMapper.getIdByRoleName("维修工");
            ids.addAll(fUserIds);
        }
        //为老人异常数据
        if(alertRule.getAlertDataType() == 0){
            //随身设备
            if(deviceData.getLocationType() == 0){
                List<Long> nUserIds = alertRuleMapper.getIdByIotIdThroughElder(field);
                ids.addAll(nUserIds);
            }
            if(deviceData.getLocationType() == 1){
                List<Long> nUserIds = alertRuleMapper.getIdByIotIdThroughBed(field);
                ids.addAll(nUserIds);
            }
        }
        //批量保存数据
        String reason = alertRule.getFunctionName()+alertRule.getOperator()+alertRule.getValue()+"持续"+alertRule.getDuration()+"周期";
        List<AlertData> alertDataList = new ArrayList<>();
        for (Long id : ids) {
            AlertData alertData = new AlertData();
            BeanUtils.copyProperties(deviceData,alertData);
            alertData.setId(null);
            alertData.setAlertRuleId(alertRule.getId());
            alertData.setAlertReason(reason);
            alertData.setType(alertRule.getAlertDataType());
            alertData.setStatus(0);
            alertData.setUserId(id);
            alertDataList.add(alertData);
        }
        alertDataService.saveBatch(alertDataList);
    }
}
